﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using HJT212_Protocol_DAL.DAO;
using HJT212_Protocol_DAL.Model;

namespace HJT212_Protocol_WebServer
{
    /// <summary>
    /// Summary description for GetClientList
    /// </summary>
    public class GetClientList : IHttpHandler
    {
        private int Count = 0;
        private string TreeGridnullStr = "\"state\":\"open\"";
        public void ProcessRequest(HttpContext context)
        {
            //不让浏览器缓存
            context.Response.Buffer = true;
            context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
            context.Response.AddHeader("pragma", "no-cache");
            context.Response.AddHeader("cache-control", "");
            context.Response.CacheControl = "no-cache";
            context.Response.ContentType = "text/plain";
            string type = context.Request["Type"];
            string _page = context.Request["page"];
            string _rows = context.Request["rows"];
            string callback = context.Request["callback"];//JqueryGet
            int page = 1, rows = 10;
            if (!string.IsNullOrEmpty(_page))
            {
                page = Convert.ToInt32(_page);
            }
            if (!string.IsNullOrEmpty(_rows))
            {
                rows = Convert.ToInt32(_rows);
            }
            string data = "";
            switch (type)
            {
                case "ClientList":
                    data = ShowOnlineClients(page, rows);
                    data = "{\"total\":\"" + Count + "\", \"rows\":" + data + "}";
                    if (!string.IsNullOrEmpty(callback))
                    {
                        data = callback + "(" + data + ")";
                    }
                    break;
                case "ClientTreeList":
                    data = GetRootClients();
                    break;
                case "SubClientTreeList":
                    int ID = int.Parse(string.Format("{0}", context.Request["ID"]));
                    data = GetSubClients(ID);
                    if (data == null)
                    {
                        data = TreeGridnullStr;
                    }
                    break;
                case "Edit":
                    ClientDao dao = new ClientDao();
                    ClientModel mdl = new ClientModel();
                    mdl.ID = int.Parse(string.Format("{0}", context.Request["ID"]));
                    mdl.ParentID = int.Parse(string.Format("{0}", context.Request["ParentID"]));
                    mdl.MN = context.Request["MN"];
                    mdl.MCNName = context.Request["MCNName"];
                    mdl.PW = context.Request["PW"];
                    string opt = context.Request["Opt"];
                    string lf = context.Request["IsLeaf"];
                    if (string.IsNullOrEmpty(lf))
                    {
                        mdl.IsLeaf = 0;
                    }
                    else
                    {
                        mdl.IsLeaf = Convert.ToInt32(lf);
                    }
                    if (opt == "insert")
                    {
                        if (!string.IsNullOrEmpty(mdl.MN) && dao.SearchDataByMn(mdl.MN))
                        {
                            data = "Exist";
                        }
                        else
                        {

                            dao.InsertData(mdl);
                            data = "ok";
                        }
                    }
                    else if (opt == "update")
                    {
                        dao.UpdateData(mdl);
                        data = "ok";
                    }
                    else if (opt == "del")
                    {
                        dao.DelData(mdl.ID.ToString());
                        data = "ok";
                    }
                    break;
            }
            context.Response.Write(data);
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        /// <summary>
        /// 显示所有在线的客户端
        /// </summary>
        private string ShowOnlineClients(int page, int rows)
        {
            try
            {

                ClientDao dao = new ClientDao();
                List<ClientModel> lst = dao.GetDbClientList();
                lst.AddRange(lst);
                lst.AddRange(lst);
                lst.AddRange(lst);
                lst.AddRange(lst);
                lst.AddRange(lst);
                Count = lst.Count();
                var data = lst.Skip(page * rows).Take(rows);

                System.Web.Script.Serialization.JavaScriptSerializer slzer =
                    new System.Web.Script.Serialization.JavaScriptSerializer();
                return slzer.Serialize(data);

            }
            catch (Exception ex)
            {

                return "0";
            }
        }

        /// <summary>
        /// 检索跟级客户端
        /// </summary>
        private string GetRootClients()
        {
            try
            {

                ClientDao dao = new ClientDao();
                List<ClientModel> lst = dao.GetDbClientList();
                var lst2 = lst.Where(itm => itm.ParentID == -1);
                if (lst2 != null && lst2.Count() > 0)
                {
                    System.Web.Script.Serialization.JavaScriptSerializer slzer =
                        new System.Web.Script.Serialization.JavaScriptSerializer();
                    lst = lst2.ToList();
                    lst.ForEach(itm =>
                                    {
                                        itm.state = "closed";
                                        itm.OnLineState = -1;
                                    });
                    return slzer.Serialize(lst);
                }
            }
            catch (Exception ex)
            {

                return "0";
            }
            return null;
        }

        /// <summary>
        /// 检索跟级客户端
        /// </summary>
        private string GetSubClients(int ParentID)
        {
            try
            {

                ClientDao dao = new ClientDao();
                List<ClientModel> lst = dao.GetDbClientList();

                var lst2 = lst.Where(itm => itm.ParentID == ParentID);
                if (lst2 != null && lst2.Count() > 0)
                {
                    System.Web.Script.Serialization.JavaScriptSerializer slzer =
                        new System.Web.Script.Serialization.JavaScriptSerializer();
                    lst = lst2.ToList();
                    lst.ForEach(itm =>
                    {
                        if (itm.IsLeaf == 1)
                        {
                            itm.state = "open";
                        }
                        else
                        {
                            itm.state = "closed";
                            itm.OnLineState = -1;
                        }
                    });
                    return slzer.Serialize(lst);
                }


            }
            catch (Exception ex)
            {

                return "0";
            }
            return null;
        }


    }
}